package com.example.xxcjgl.utils

import android.content.Context
import android.content.SharedPreferences
import com.example.xxcjgl.data.models.User

//Preferences.kt
class PreferencesManager(private val context: Context) {
    private val sharedPreferences: SharedPreferences by lazy {
        context.getSharedPreferences("xxcjgl_prefs", Context.MODE_PRIVATE)
    }

    // 用户相关
    fun saveUser(user: User) {
        sharedPreferences.edit().apply {
            putString("user_data", Gson().toJson(user))
            apply()
        }
    }

    fun getCurrentUser(): User? {
        val userJson = sharedPreferences.getString("user_data", null)
        return try {
            Gson().fromJson(userJson, User::class.java)
        } catch (e: Exception) {
            null
        }
    }

    fun saveUsername(username: String) {
        sharedPreferences.edit().putString("username", username).apply()
    }

    fun getSavedUsername(): String {
        return sharedPreferences.getString("username", "") ?: ""
    }

    fun setLoggedIn(isLoggedIn: Boolean) {
        sharedPreferences.edit().putBoolean("is_logged_in", isLoggedIn).apply()
    }

    fun isLoggedIn(): Boolean {
        return sharedPreferences.getBoolean("is_logged_in", false)
    }

    fun clearUserData() {
        sharedPreferences.edit().clear().apply()
    }

    // 应用设置
    fun setRememberMe(remember: Boolean) {
        sharedPreferences.edit().putBoolean("remember_me", remember).apply()
    }

    fun shouldRememberMe(): Boolean {
        return sharedPreferences.getBoolean("remember_me", false)
    }

    // 加密相关
    fun saveLastEncryptionKey(key: String) {
        sharedPreferences.edit().putString("last_encryption_key", key).apply()
    }

    fun getLastEncryptionKey(): String {
        return sharedPreferences.getString("last_encryption_key", "") ?: ""
    }
}